/*
 * @FileDescription: axios封装
 * @Author: zhaijiansheng
 * @Date: 2023-09-01 11:01:46
 * @LastEditors: zhaijiansheng
 * @LastEditTime: 2023-12-21 21:06:12
 */
import axios from "axios";
// 错误编码
import errorCode from "@/utils/errorCode";
const request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 7000
});
// 请求拦截器
request.interceptors.request.use((config) => {
    return config;
});

// 添加响应拦截器
request.interceptors.response.use(
    (res) => {
        // 未设置状态码则默认成功状态
        const code = res.data.code || 200;
        // 获取错误信息
        const msg = errorCode[code] || res.data.msg || errorCode["default"];
        if (code == 500) {
            ElMessage({ message: msg, type: "error" });
            return Promise.reject(new Error(msg))
        } else if (code !== 200) {
            ElNotification.error({ title: msg });
            return Promise.reject(new Error(msg));
        } else {
            return Promise.resolve(res.data);
        }
    },
    (error) => {
        let { message } = error;
        if (message == "Network Error") {
            message = "后端接口连接异常";
        } else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        } else if (message.includes("Request failed with status code")) {
            message = "系统接口" + message.substr(message.length - 3) + "异常";
        }
        ElMessage({ message: message, type: "error", duration: 5 * 1000 });
        // 对响应错误做点什么
        return Promise.reject(error);
    }
);

export default request;
